﻿using DevExpress.Utils.Filtering.Internal;
using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinForm_Mes.WorkingManagement.Technological;
using static DevExpress.Drawing.Printing.Internal.DXPageSizeInfo;

namespace WinForm_Mes.Process
{
    public partial class TechnologicalFlow : DevExpress.XtraEditors.XtraForm
    {
        public TechnologicalFlow()
        {
            InitializeComponent();
            gridView1.OptionsSelection.MultiSelect = true;
            gridView1.OptionsSelection.MultiSelectMode = DevExpress.XtraGrid.Views.Grid.GridMultiSelectMode.CheckBoxRowSelect;
        }

        private async void TechnologicalFlow_Load(object sender, EventArgs e)
        {
            await LoadData();
        }
        private int PageIndex = 1;
        private int PageSize = 10;
        private int total = 10;
        private int PageCount = 0;
        // 加载数据
        private async Task LoadData(string queryParams = "")
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:5053/");
                
                // 拼接查询参数
                
                var response = await client.GetAsync($"/api/ProcessManagement/GetTechnologicalFlowList{queryParams}");
                if (response.IsSuccessStatusCode)
                {
                    var json = await response.Content.ReadAsStringAsync();
                    var list = JsonConvert.DeserializeObject<Rootobject>(json);
                    gridControl1.DataSource = list.items;
                    PageIndex = list.pageIndex;
                    PageSize = list.pageSize;
                    total = list.total;
                    PageCount = (int)Math.Ceiling((double)total / PageSize);
                    labelControl4.Text = $"，共{total}条数据，第{PageIndex}/{PageCount}页";

                }
                else
                {
                    MessageBox.Show("加载数据失败！");
                }
            }
        }

        // 查询按钮事件，改为 async
        private async void FindTechnologicalFlowClick(object sender, EventArgs e)
        {
            await CheckAndPage();
        }

        // 查询逻辑，改为 async 并传递参数
        public async Task CheckAndPage()
        {
            var technologicalCode = textEdit1.Text.Trim();
            var technologicalName = textEdit2.Text.Trim();
            var isEnabled = comboBoxEdit1.SelectedItem.ToString();
            if (isEnabled == "请输入")
            {
                isEnabled = "";
            }
            else if (isEnabled == "启用")
            {
                isEnabled = "true";
            }
            else if (isEnabled == "禁用")
            {
                isEnabled = "false";
            }

            try
            {
                string queryParams = $"?TechnoloigcalCode={technologicalCode}&TechnoloigcalName={technologicalName}&IsEnabled={isEnabled}&PageIndex={PageIndex}&PageSize={PageSize}";
                await LoadData(queryParams);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发生异常: {ex.Message}", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        // 添加重置功能
        private void ResetTechnologicalFlowClick(object sender, EventArgs e)
        {
            // 清空查询条件
            textEdit1.Text = "";
            textEdit2.Text = "";
            comboBoxEdit1.Text = "";
        }

        // 新增
        private async void AddButton_Click(object sender, EventArgs e)
        {
            var addForm = new AddTechnologicalForm(); // 你需要新建一个编辑窗体
            if (addForm.ShowDialog() == DialogResult.OK)
            {
                var newItem = addForm.GetItem();
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://localhost:5053/");
                    var json = JsonConvert.SerializeObject(newItem);
                    var content = new StringContent(json, Encoding.UTF8, "application/json");
                    var response = await client.PostAsync("/api/ProcessManagement/AddTechnologicalFlow", content);
                    if (response.IsSuccessStatusCode)
                        await LoadData();
                    else
                        MessageBox.Show("新增失败！");
                }
            }
        }

        // 修改
        private async void EditButton_Click(object sender, EventArgs e)
        {
            var selected = GetSelectedItem();
            if (selected == null)
            {
                MessageBox.Show("请选择要修改的数据！");
                return;
            }
            
            var editForm = new UpdateTechnologicalForm(selected);
            if (editForm.ShowDialog() == DialogResult.OK)
            {
                var updateItem = editForm.GetItem();
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://localhost:5053/");
                    var json = JsonConvert.SerializeObject(updateItem);
                    var content = new StringContent(json, Encoding.UTF8, "application/json");
                    var response = await client.PostAsync("/api/ProcessManagement/UpdateTechnologicalFlow", content);
                    if (response.IsSuccessStatusCode) {
                        MessageBox.Show("修改成功！");
                        await LoadData();
                    }
                    else
                        MessageBox.Show("修改失败！");
                }
            }
        }

        // 删除
        private async void DeleteButton_Click(object sender, EventArgs e)
        {
            var selected = GetSelectedItem();

            if (selected == null)
            {
                MessageBox.Show("请选择要删除的数据！");
                return;
            }
            if (gridView1.GetSelectedRows().Length > 1)
            {
                MessageBox.Show("只能选择一条数据进行删除！");
                return;
            }
            if (MessageBox.Show("确定要删除吗？", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://localhost:5053/");
                    var response = await client.PostAsync($"/api/ProcessManagement/DeleteTechnologicalFlow?id={selected.Id}",null);
                    if (response.IsSuccessStatusCode)
                        await LoadData();
                    else
                        MessageBox.Show("删除失败！");
                }
            }
        }

        // 获取选中行
        private TechnologicalFlowItem GetSelectedItem()
        {
            if (gridView1.GetSelectedRows().Length > 0)
            {
                int rowHandle = gridView1.GetSelectedRows()[0];
                return gridView1.GetRow(rowHandle) as TechnologicalFlowItem;
            }
            return null;
        }

        private async void simpleButton7_Click(object sender, EventArgs e)
        {
            if (PageIndex>1 && PageIndex<=PageCount) {
                PageIndex -= 1;
                await CheckAndPage();
            }
        }

        private async void simpleButton8_Click(object sender, EventArgs e)
        {
            if (PageIndex >= 1 && PageIndex < PageCount)
            {
                PageIndex += 1;
                await CheckAndPage();
            }
        }

        private async void textEdit3_EditValueChanged(object sender, EventArgs e)
        {
            int num;
            if (!int.TryParse(textEdit3.Text, out num) || num < 1)
            {
                textEdit3.Text = PageIndex.ToString();
                return;
            }
            if (num > PageCount)
            {
                textEdit3.Text = PageIndex.ToString();
                return;
            }
            PageIndex = num;
            await CheckAndPage();
        }
    }
}

public class TechnologicalFlowItem
{
    public long Id { get; set; }
    /// <summary>
    /// 工艺编号
    /// </summary>
    public string TechnologicalCode { get; set; }

    /// <summary>
    /// 工艺名称
    /// </summary>
    public string TechnologicalName { get; set; }

    /// <summary>
    /// 是否启用，默认启用
    /// </summary>
    public bool IsEnabled { get; set; } = true;

    /// <summary>
    /// 工艺说明
    /// </summary>
    public string TechnologicalDescription { get; set; }

    /// <summary>
    /// 备注
    /// </summary>
    public string Remarks { get; set; }
}


public class Rootobject
{
    public int total { get; set; }
    public int pageIndex { get; set; }
    public int pageSize { get; set; }
    public TechnologicalFlowItem[] items { get; set; }
    public int code { get; set; }
    public string message { get; set; }
    public object data { get; set; }
}

public static class PaginationHelper
{
    public static async Task<Rootobject> GetPagedListAsync<T>(string url, int pageIndex, int pageSize, Dictionary<string, string> extraParams = null)
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:5053/");
            var paramList = new List<string>
            {
                $"pageIndex={pageIndex}",
                $"pageSize={pageSize}"
            };
            if (extraParams != null)
            {
                foreach (var kv in extraParams)
                {
                    paramList.Add($"{kv.Key}={kv.Value}");
                }
            }
            string paramStr = string.Join("&", paramList);
            var response = await client.GetAsync($"{url}?{paramStr}");
            if (response.IsSuccessStatusCode)
            {
                var json = await response.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<Rootobject>(json);
            }
            else
            {
                throw new Exception("分页数据请求失败！");
            }
        }
    }
}





